package cn.xspace.app.filemg.fragment;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.DateUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.bean.ImgPackInfo;
import cn.xspace.app.filemg.util.CallBack;
import cn.xspace.app.filemg.view.FileImgAdapter;
import cn.xspace.app.filemg.view.ImgGridAdapter;

public class FileImgFragment extends Fragment implements CallBack{
	private Context mContext;
	private ArrayList<ImgPackInfo> packList=new ArrayList<ImgPackInfo>();
	private FileImgAdapter mAdapter;
	private ExpandableListView mListView;
	private boolean checkFlag, imgCheckFlag;
	private static CallBack mCallBack;
	private boolean isOver = true;
	private boolean isUpdate = true;
	private ImgGridAdapter mImgGridAdapter;
	private ArrayList<FileInfo> imgList;
	private boolean isOpen = true;
	private MyAsyncTask mMyAsyncTask;
	private ImgPackInfo packInfo;
	private HashMap<String, ArrayList<FileInfo>> mGruopMap = new HashMap<String, ArrayList<FileInfo>>();
	private ChooseFileInfo chooseInfo = new ChooseFileInfo();
	public static FileImgFragment newInstance(CallBack callBack) {
		FileImgFragment newFragment = new FileImgFragment();
		mCallBack = callBack;
		return newFragment;

	}

	public void updateFile(ImgPackInfo info) {
		try {

			for (ImgPackInfo packInfo : packList) {
				if (info.getPackName().equals(packInfo.getPackName())) {
					return;
				}
			}
			packList.add(info);
			handler.sendEmptyMessageDelayed(0, 2000);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				isUpdate = true;
				if (mAdapter != null) {
					try {
						mAdapter.notifyDataSetInvalidated();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					mAdapter = new FileImgAdapter(mContext, packList,FileImgFragment.this);
					mListView.setAdapter(mAdapter);
				}
				break;
			case 1:
				if (mListView != null)
					mListView.expandGroup(0);
				break;

			default:
				break;
			}
		}
	};

	//
	public void queryOver() {
		isOver = true;
		handler.sendEmptyMessage(1);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = FileImgFragment.this.getActivity();
//		packList = BaseDbMg.getInstance().getSendSql().querySendImg("img");

//		 addImg();
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		handler.removeMessages(0);
		handler.removeMessages(1);
		super.onDestroy();
	}
	private class MyAsyncTask extends AsyncTask {
		@Override
		protected Object doInBackground(Object... arg0) {
			Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			ContentResolver mContentResolver = getActivity()
					.getContentResolver();

			// 只查询jpeg和png的图片
			Cursor mCursor = mContentResolver.query(mImageUri, null,
					MediaStore.Images.Media.MIME_TYPE + "=? or "
							+ MediaStore.Images.Media.MIME_TYPE + "=?",
					new String[] { "image/jpeg", "image/png" },
					MediaStore.Images.Media.DATE_MODIFIED);
			ArrayList<FileInfo> testList=null;
			ImgPackInfo imgTest=null;
			while (mCursor.moveToNext()) {
				// 获取图片的路径
				String path = mCursor.getString(mCursor
						.getColumnIndex(MediaStore.Images.Media.DATA));

				// 获取该图片的父路径名
				String parentName = new File(path).getParentFile()
						.getName();
				
				FileInfo imgInfo=new FileInfo();
				imgInfo.setName( mCursor.getString(mCursor
						.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)));
				imgInfo.setPath(path);
				imgInfo.setPackageName(parentName);
				imgInfo.setSize(mCursor.getLong(mCursor.getColumnIndex( MediaStore.Images.Media.SIZE)));
				File tFile=new File(path);
				imgInfo.setTime(DateUtils.timeMillisToDateTimeString(tFile.lastModified(),DateUtils.FORMAT_5));
				for(FileInfo cInfo: chooseInfo.getFileList()){
					if(cInfo.getPath().equals(imgInfo.getPath())){
						imgInfo.setCheckFlag(true);
					}
				}
			
				// 根据父路径名将图片放入到mGruopMap中
				if (!mGruopMap.containsKey(parentName)) {
					testList=new ArrayList<FileInfo>();
					testList.add(imgInfo);
					imgTest=null;
					mGruopMap.put(parentName, testList);
				} else {
					testList.add(imgInfo);
				}
				if(imgTest==null){
					imgTest=new ImgPackInfo();
					imgTest.setPackPath(tFile.getParentFile().getPath());
					imgTest.setPackName(parentName);
					imgTest.setIocPath(path);
					imgTest.setImgList(testList);
					packList.add(imgTest);
				}
			
			}

			mCursor.close();
			System.out.println("---------------------------------MyAsyncTask-"+packList.size());
			// 通知Handler扫描图片完成
			handler.sendEmptyMessage(0);
			handler.sendEmptyMessage(1);
			return null;
		}

	}

	private void addImg() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(getActivity(), "暂无外部存储", Toast.LENGTH_SHORT).show();
			return;
		}

		new Thread(new Runnable() {

			@Override
			public void run() {
				

			}
		}).start();
		
	}
	public void initChooseData(ChooseFileInfo chooseInfo){
        this.chooseInfo=chooseInfo;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(BaseRProxy.file_img, container, false);
//		mGridView = (GridView) view.findViewById(RProxy.gridview);
		mListView = (ExpandableListView) view.findViewById(BaseRProxy.favorite_webs_list_expandlv);
		if(packList.size()!=0){
			mAdapter = new FileImgAdapter(mContext, packList,FileImgFragment.this);
			mListView.setAdapter(mAdapter);
		}else{
		   mMyAsyncTask = new MyAsyncTask();
		   mMyAsyncTask.execute();
		}
		return view;

	}

	@Override
	public void checkedInfo(FileInfo info) {
		// TODO Auto-generated method stub
		info.setCheckFlag(!info.isCheckFlag());
		if(info.isCheckFlag()){
			if(chooseInfo.getFileList().size()>=10){
				info.setCheckFlag(!info.isCheckFlag());
				Toast.makeText(getActivity(), "最多能选10个文件", Toast.LENGTH_SHORT).show();
			}
			if((chooseInfo.getSize()+info.getSize())>(1048576*100)){
				info.setCheckFlag(!info.isCheckFlag());
				Toast.makeText(getActivity(), "所选文件已超过100MB", Toast.LENGTH_SHORT).show();
			}
		}
		mAdapter.notifyDataSetChanged();
	    mCallBack.checkedInfo(info);
	}
}
